import axios from 'axios'
import qs from 'qs'
import { refreshToken } from '../api/api'



import {
  Loading,
  Message,
  MessageBox
} from 'element-ui'
import store from '../store'
import router from '../router'
import { sessionStorage } from 'src/assets/js/storage'

if (!store.state.token) {
  store.commit('SET_TOKEN', sessionStorage.getItem('token'))
}

// axios 配置

const http = axios.create({
  baseURL: 'http://www.ccppvip.com:8081/',
  // baseURL: 'http://192.168.0.119:8081/',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  transformRequest: [function(data, headers) {
    headers.token = store.state.token
    if (headers['Content-type'] === 'multipart/form-data') {
      return data
    } else {
      return qs.stringify(data)
    }
  }],
  withCredentials: true  // 加了这段就可以跨域了
})


var loadingInstance
// 请求拦截器
http.interceptors.request.use(config => {
  loadingInstance = Loading.service({
    fullscreen: true,
    lock: true,
    text: '正在请求数据...'
  })

  // 开发环境下，如果请求是 post,put,patch,则打印数据体，方便调试
  if (process.env.NODE_ENV === 'development') {
    const { method } = config
    if (method === 'post' || method === 'put' || method === 'patch') {
      console.log(config.data)
    }
  }

  return config
}, error => {
  loadingInstance.close()
  Message.error({
    message: '请求失败'
  })
  return Promise.reject(error)
})

// 响应拦截器
http.interceptors.response.use(res => {
  loadingInstance.close()
  // console.log(res)
  return res.data
}, error => {
  loadingInstance.close()
  if (error && error.response) {
    switch (error.response.data.code) {
      // 20006 token失效
      case 200006:
        const para = Object.assign({}, {
          refreshToken: sessionStorage.getItem('refreshToken'),
          userId: sessionStorage.getItem('userId')
        })
        refreshToken(para).then(res => {
          console.log(res + '===================== refreshToken res')
          if (res.code === 200005) {
            MessageBox.alert('身份信息已过期，请重新登陆', '提示', {
              confirmButtonText: '重新登陆',
              showClose: false,
              type: 'error',
              callback: action => {
                router.replace({
                  path: '/login',
                  query: {
                    redirect: router.currentRoute.fullPath
                  }
                })
              }
            })
          }
          // 替换之前的token  refreshtoken

          store.commit('SET_TOKEN', res.data.token)
          store.commit('SET_REFRESHTOKEN', res.data.refreshToken)

          // 替换headertoken // 重新发起请求
          let config = error.config
          // 把参数从 字符串 变成 对象
          config.data = qs.parse(error.config.data)
          return axios.request(config)
        })

        break

      // 403 服务器拒绝访问
      case 403:
        router.push('/error/403')
        break

      // 404 访问的资源不存在
      case 404:
        router.push('/error/404')
        break

      // 500 服务器错误
      case 500:
        router.push('/error/500')
        break
    }

    return Promise.reject(error)
  }
})

export default http
